from PIL import Image
from PIL import ImageFilter
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
###########################################
##图像滤波
##
##PIL显示图片数字范围0-255
###########################################
	


#输出文件
def write_txt(name, _list):
	with open (f'..\\image-data\\{name}.txt', 'w') as f:
		for i in range(len(_list)):
			f.write(f'{_list[i]:08b}')
			if i != len(_list)-1:
				f.write('\n')

#读取数据整形
def img_data_reshape(im_data, width, height):
	_list = [[] for i in range(height)]
	for i in range(width):
		for j in range(height):
			_list[j].append(bin2dec(im_data[i+j*width]))
	return _list


#str的二进制转十进制
def bin2dec(_str):
	val = 0
	for i in range(len(_str)):
		val = val + int(_str[i]) * 2**(7-i)
	return val


#读取图片rgb图片
def read_rgb_img(name, blur):
	f = Image.open(f'..\\image\\{name}.png')
	#增加高斯模糊
	if blur:
		f = f.filter(ImageFilter.GaussianBlur(radius=2))
	pix = f.load()
	width = f.size[0]
	height = f.size[1]
	r = []
	g = []
	b = []
	for i in range(height):
		for j in range(width):
			r.append(pix[j,i][0])
			g.append(pix[j,i][1])
			b.append(pix[j,i][2])
	write_txt(f'{name}_r', r)
	write_txt(f'{name}_g', g)
	write_txt(f'{name}_b', b)
	f.show()
	f.save(f'..\\image-processed\\{name}-before-processing.tif')
	return width, height

def read_gray_img(name):
	f = Image.open(f'..\\image\\{name}.tif')
	pix = f.load()
	width = f.size[0]
	height = f.size[1]
	pix_data = []
	for i in range(height):
		for j in range(width):
			pix_data.append(pix[j,i])
	write_txt(f'{name}_gray', pix_data)
	f.show()
	f.save(f'..\\image-processed\\{name}-before-processing.tif')
	return width, height



#读取单个文件整形
def read_rgb_data(name, width, height):
	with open(f'..\\image-data\\{name}.txt', 'r', newline = '') as f:
		read_stream = f.read().splitlines()
	data_reshape = img_data_reshape(read_stream, width, height)
	data_array = np.array(data_reshape)
	return data_array


#读取文件并且整形
def read_img_data(name, width, height):
	r = read_rgb_data(f'{name}_r_sharpen', width, height)
	g = read_rgb_data(f'{name}_g_sharpen', width, height)
	b = read_rgb_data(f'{name}_b_sharpen', width, height)
	img_data = [[] for i in r]
	for i in range(len(r)):
		for j in range(len(r[i])):
			img_data[i].append([r[i][j], g[i][j], b[i][j]])
	img = Image.fromarray(np.uint8(img_data))
	img.show()
	img.save(f'..\\image-processed\\{name}-after-processing.tif')

#读取灰度图滤波之后
def read_gray_img_data(name, width, height):
	pix_data = read_rgb_data(f'{name}_gray_sharpen', width, height)
	img_data = [[] for i in range(height)]
	for i in range(height):
		for j in range(width):
			img_data[i].append(pix_data[i, j])
	img = Image.fromarray(np.uint8(img_data))
	img.show()
	img.save(f'..\\image-processed\\{name}-after-processing.tif')


# 高斯模糊处理
blur_flag = 0

# 读图片，输出rgb
width, height = read_gray_img('lena')#read_rgb_img('lena', blur_flag)

# 读取rgb文件，输出图片
read_gray_img_data('lena', width, height)

